﻿namespace ScrumLite.WebUx.SharedViews
{
    using System;
    using System.Web.Mvc;
    using ScrumLite.WebUx.Models;
    using System.Web.Routing;
    using System.Reflection;

    public class ContextViewPage<TViewData> : ViewPage<TViewData> where TViewData : ContextViewData
    {
        public new BaseHtmlHelper Html { get; set; }
        public new BaseUrlHelper Url { get; set; }

        protected override void OnLoad(EventArgs e)
        {
            this.Html = new BaseHtmlHelper(ViewContext);
            this.Url = new BaseUrlHelper(ViewContext);
            this.Title = ViewData.ProjectName + " - " + ViewData.ViewTitle;
            base.OnLoad(e);
        }
    }


    public class BaseHtmlHelper : HtmlHelper
    {
        public BaseHtmlHelper(ViewContext context)
            : base(context)
        {

        }
        public string ActionLink(string linkText, object values)
        {
            RouteValueDictionary revalues = new RouteValueDictionary();
            foreach (PropertyInfo p in values.GetType().GetProperties())
            {
                if (p.Name != "Action" && p.Name != "Controller")
                {
                    revalues.Add(p.Name, p.GetValue(values, null));
                }
            }

            return base.ActionLink(linkText, values.GetType().GetProperty("Action").GetValue(values, null).ToString(), values.GetType().GetProperty("Controller").GetValue(values, null).ToString(), revalues);
        }
    }

    public class BaseUrlHelper : UrlHelper
    {
        public BaseUrlHelper(ViewContext context)
            : base(context)
        {

        }

        public string Action(object values)
        {
            RouteValueDictionary revalues = new RouteValueDictionary();
            foreach (PropertyInfo p in values.GetType().GetProperties())
            {
                if (p.Name != "Action" && p.Name != "Controller")
                {
                    revalues.Add(p.Name,p.GetValue(values, null));
                }
            }
            return base.Action(values.GetType().GetProperty("Action").GetValue(values, null).ToString(), values.GetType().GetProperty("Controller").GetValue(values, null).ToString(), revalues);
        }
    }
}
